<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="书名" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入书名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input
            v-model="queryParams.author"
            placeholder="请输入作者"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="ISBN" prop="isbn">
          <el-input
            v-model="queryParams.isbn"
            placeholder="请输入ISBN"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="图书状态" clearable style="width: 200px">
            <el-option label="可借阅" value="AVAILABLE" />
            <el-option label="已借出" value="BORROWED" />
            <el-option label="维护中" value="MAINTENANCE" />
            <el-option label="已下架" value="UNAVAILABLE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <el-row :gutter="16" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Plus"
            class="toolbar-button is-primary"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            icon="Edit"
            :disabled="single"
            class="toolbar-button is-success"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="Delete"
            :disabled="multiple"
            class="toolbar-button is-danger"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="Download"
            class="toolbar-button is-warning"
            @click="handleExport"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            icon="Upload"
            class="toolbar-button is-info"
            @click="handleImport"
          >导入</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 图书表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="bookList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="封面" align="center" width="80">
          <template #default="scope">
            <el-image
              style="width: 50px; height: 60px"
              :src="scope.row.coverImage || '/default-book.jpg'"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="书名" align="center" prop="title" :show-overflow-tooltip="true" />
        <el-table-column label="作者" align="center" prop="author" width="120" />
        <el-table-column label="ISBN" align="center" prop="isbn" width="150" />
        <el-table-column label="分类" align="center" prop="categoryName" width="100" />
        <el-table-column label="总数量" align="center" prop="totalQuantity" width="80" />
        <el-table-column label="可借数量" align="center" prop="availableQuantity" width="80" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag
              :type="getStatusType(scope.row.status)"
              disable-transitions
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-operation-wrapper">
              <el-button
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                class="table-operation-button is-primary"
                size="small"
              >修改</el-button>
              <el-button
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                class="table-operation-button is-danger"
                size="small"
              >删除</el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button
                  type="warning"
                  class="table-operation-button is-warning"
                  size="small"
                >
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="handlePublish" icon="VideoPlay">上架</el-dropdown-item>
                    <el-dropdown-item command="handleUnpublish" icon="VideoPause">下架</el-dropdown-item>
                    <el-dropdown-item command="handleStatistics" icon="DataAnalysis">借阅统计</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改图书配置对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="bookFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="书名" prop="title">
              <el-input v-model="form.title" placeholder="请输入书名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="form.author" placeholder="请输入作者" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="ISBN" prop="isbn">
              <el-input v-model="form.isbn" placeholder="请输入ISBN" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出版社" prop="publisher">
              <el-input v-model="form.publisher" placeholder="请输入出版社" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择分类">
                <el-option label="文学" value="1" />
                <el-option label="科技" value="2" />
                <el-option label="历史" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总数量" prop="totalQuantity">
              <el-input-number v-model="form.totalQuantity" :min="1" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出版日期" prop="publishDate">
              <el-date-picker
                v-model="form.publishDate"
                type="date"
                placeholder="选择出版日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number v-model="form.price" :min="0" :precision="2" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="简介" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入图书简介" :rows="4" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBookPage, createBook, updateBook, deleteBook, publishBook, unpublishBook } from '@/api/library'
import Pagination from '@/components/Pagination/index.vue'

// 响应式数据
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const bookList = ref([])
const title = ref('')
const open = ref(false)
const queryFormRef = ref()
const bookFormRef = ref()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: undefined,
  author: undefined,
  isbn: undefined,
  status: undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  title: undefined,
  author: undefined,
  isbn: undefined,
  publisher: undefined,
  categoryId: undefined,
  totalQuantity: 1,
  publishDate: undefined,
  price: 0,
  description: undefined
})

// 表单校验规则
const rules = reactive({
  title: [{ required: true, message: '书名不能为空', trigger: 'blur' }],
  author: [{ required: true, message: '作者不能为空', trigger: 'blur' }],
  isbn: [{ required: true, message: 'ISBN不能为空', trigger: 'blur' }],
  categoryId: [{ required: true, message: '分类不能为空', trigger: 'change' }],
  totalQuantity: [{ required: true, message: '总数量不能为空', trigger: 'blur' }]
})

// 获取图书列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getBookPage(queryParams)
    if (response.code === 200) {
      bookList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取图书列表失败')
    }
  } catch (error) {
    console.error('获取图书列表失败:', error)
    ElMessage.error('获取图书列表失败')
  } finally {
    loading.value = false
  }
}

// 状态类型
const getStatusType = (status) => {
  const statusMap = {
    'AVAILABLE': 'success',
    'BORROWED': 'warning',
    'MAINTENANCE': 'info',
    'UNAVAILABLE': 'danger'
  }
  return statusMap[status] || 'info'
}

// 状态文本
const getStatusText = (status) => {
  const statusMap = {
    'AVAILABLE': '可借阅',
    'BORROWED': '已借出',
    'MAINTENANCE': '维护中',
    'UNAVAILABLE': '已下架'
  }
  return statusMap[status] || '未知'
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加图书'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  const bookId = row.id || ids.value[0]
  Object.assign(form, row)
  open.value = true
  title.value = '修改图书'
}

// 删除按钮操作
const handleDelete = (row) => {
  const bookIds = row.id ? [row.id] : ids.value
  ElMessageBox.confirm('是否确认删除图书编号为"' + bookIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteBook(bookIds[0])
    getList()
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 更多操作触发
const handleCommand = (command, row) => {
  switch (command) {
    case 'handlePublish':
      handlePublish(row)
      break
    case 'handleUnpublish':
      handleUnpublish(row)
      break
    case 'handleStatistics':
      handleStatistics(row)
      break
    default:
      break
  }
}

// 上架图书
const handlePublish = async (row) => {
  try {
    await publishBook(row.id)
    ElMessage.success('上架成功')
    getList()
  } catch (error) {
    console.error('上架失败:', error)
  }
}

// 下架图书
const handleUnpublish = async (row) => {
  try {
    await unpublishBook(row.id)
    ElMessage.success('下架成功')
    getList()
  } catch (error) {
    console.error('下架失败:', error)
  }
}

// 借阅统计
const handleStatistics = (row) => {
  ElMessage.info('借阅统计功能开发中...')
}

// 导出按钮操作
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 导入按钮操作
const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: undefined,
    title: undefined,
    author: undefined,
    isbn: undefined,
    publisher: undefined,
    categoryId: undefined,
    totalQuantity: 1,
    publishDate: undefined,
    price: 0,
    description: undefined
  })
  bookFormRef.value?.resetFields()
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 提交表单
const submitForm = () => {
  bookFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          await updateBook(form.id, form)
          ElMessage.success('修改成功')
        } else {
          await createBook(form)
          ElMessage.success('新增成功')
        }
        open.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

// 时间格式化
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}

.toolbar-card {
  margin-bottom: 16px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
